package com.hyw.trace.configuration.sample.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import com.hyw.trace.configuration.sample.annotation.JointPointType;
import com.hyw.trace.configuration.sample.annotation.TraceSource;
import com.hyw.trace.configuration.sampler.AbstractSamplerTemplate;

@Aspect
public class TraceSourceAspect {

  private AbstractSamplerTemplate traceTemplate;

  public TraceSourceAspect(AbstractSamplerTemplate traceSamplerTemplate) {
    this.traceTemplate = traceSamplerTemplate;
  }

  @Around(value = "@annotation(traceSource)")
  public Object around(ProceedingJoinPoint joinPoint, TraceSource traceSource) throws Throwable {
    Object ret = null;
    if (traceSource.jointPoint() == JointPointType.Before) {
      traceTemplate.run(joinPoint.getArgs(), traceSource);
    }
    try {
      ret = joinPoint.proceed();
      return ret;
    } finally {
      if (traceSource.jointPoint() == JointPointType.After) {
        traceTemplate.run(joinPoint.getArgs(), traceSource);
      } else if (traceSource.jointPoint() == JointPointType.Result) {
        traceTemplate.run(new Object[] { ret }, traceSource);
      }
    }

  }

}
